package com.ai_daily.aitiantian.util;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.RectF;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.VectorDrawable;

public class DrawableUtil {
    /**
     * 将Drawable转换为Bitmap
     *
     * @param drawable     要转换的Drawable
     * @param cornerRadius 圆角半径
     * @return Bitmap类型的图像
     */
    public static Bitmap drawableToBitmap(Drawable drawable, float cornerRadius) {
        Bitmap bitmap;
        if (drawable instanceof BitmapDrawable) {
            bitmap = ((BitmapDrawable) drawable).getBitmap();
        } else if (drawable instanceof VectorDrawable) {
            bitmap = vectorDrawableToBitmap((VectorDrawable) drawable);
        } else {
            int width = drawable.getIntrinsicWidth();
            int height = drawable.getIntrinsicHeight();
            bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
            Canvas canvas = new Canvas(bitmap);
            drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
            drawable.draw(canvas);
        }

        if (cornerRadius > 0) {
            bitmap = getRoundedCornerBitmap(bitmap, cornerRadius);
        }

        return bitmap;
    }

    /**
     * 将VectorDrawable转换为Bitmap
     *
     * @param vectorDrawable 要转换的VectorDrawable
     * @return Bitmap类型的图像
     */
    private static Bitmap vectorDrawableToBitmap(VectorDrawable vectorDrawable) {
        int width = vectorDrawable.getIntrinsicWidth();
        int height = vectorDrawable.getIntrinsicHeight();
        Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        vectorDrawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
        vectorDrawable.draw(canvas);
        return bitmap;
    }

    /**
     * 获取圆角Bitmap
     *
     * @param bitmap       原始Bitmap
     * @param cornerRadius 圆角半径
     * @return 圆角Bitmap
     */
    private static Bitmap getRoundedCornerBitmap(Bitmap bitmap, float cornerRadius) {
        Bitmap roundedBitmap = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(roundedBitmap);
        Paint paint = new Paint();
        paint.setAntiAlias(true);
        paint.setShader(new android.graphics.BitmapShader(bitmap, android.graphics.Shader.TileMode.CLAMP, android.graphics.Shader.TileMode.CLAMP));
        Path path = new Path();
        path.addRoundRect(new RectF(0, 0, bitmap.getWidth(), bitmap.getHeight()), cornerRadius, cornerRadius, Path.Direction.CW);
        canvas.drawPath(path, paint);
        return roundedBitmap;
    }
}
